package com.ruoyi.business.dbopt.utils;

import java.io.File;
import java.io.IOException;

public class FileUtil {

    /**
     * 创建目录+文件
     * @param path
     * @return
     */
    public static File create(String path){
        if (path == null){
            return null;
        }
        File destFile = new File(path);
        if (destFile.exists()){
            return destFile;
        }

        String sp = File.separator;
        String lastPath = path.substring(path.lastIndexOf(sp) + 1);

        // 只有路径
        if (lastPath.trim().equals(StringPool.EMPTY) || !lastPath.contains(".")){
            if(destFile.mkdirs()){
                return destFile;
            }else {
                throw new CommonException(String.format("创建目录错误 %s", path));
            }
        }

        // 路径+文件
        String firstPath = path.substring(0, path.lastIndexOf(sp));
        File filePath = new File(firstPath);
        if (!filePath.exists()){
            if(!filePath.mkdirs()){
                throw new CommonException(String.format("创建目录错误 %s", filePath));
            }
        }

        try {
            if(!destFile.createNewFile()){
                throw new CommonException(String.format("创建文件错误 %s", path));
            }
        }catch (IOException e){
            throw new CommonException(String.format(String.format("创建文件错误1 %s", path)), e);
        }

        return destFile;
    }


    public static void main(String[] args) {
        System.out.println(create("d:\\aa\\bb\\2.w"));
    }
}
